import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {config} from '../../shared/smartadmin.config';
import { JsonApiService } from "app/core/api/json-api.service";
declare var $:any;
@Component({
	selector: 'app-batch-calibration',
	templateUrl: './batch-calibration.component.html',
	styleUrls: ['./batch-calibration.component.css']
})
export class BatchCalibrationComponent implements OnInit{
	loadometerData = [];
//	calibrationType:string = '1';//标定方式
	tableType:string = '0';//表类型默认表
	weightRangeTime:string = '30';//默认地磅区间1个月
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	carNumbers:string = '';
	deviceIds:string = '';
	selectedCarNumber:any = [];//checkbox选中车辆
	carList:any = [];//根据公司拉取车辆
	weightCount:string|number = '6';
	beforeTime = '1';
	afterTime = '0';
	
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	TselectedCompanyId:string = '';
	TselectedCompanyName:string = '';
	TcarNumber:string = '';
	TdeviceId:string = '';
	Ttype:string = '';
	Tstatus:string = '';
	searchKey:string = '';
	startTime:string = '';
	endTime :string = '';
	constructor(private router: Router,private jsonApiService: JsonApiService) {}
	ngOnInit() {
		this.load();
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			this.initCarTree();
			var s_car_tree_box = document.getElementById('s_car_tree_box');
			var car_input = document.getElementById('car_input');
			var carNumbers_clear = document.getElementById('carNumbers_clear')
			//公司树弹窗显示隐藏交互事件
			var html = document.getElementsByTagName('html')[0];
			html.onclick=function(e:any){
				if(s_car_tree_box.contains(e.target)||e.target == car_input||e.target == carNumbers_clear){//判断点击是否在下拉框内
					if(e.target.className == 'jstree-anchor jstree-hovered jstree-clicked jstree-search'){
						s_car_tree_box.className = s_car_tree_box.className.replace("tree_open","");
					}
				}else{
					s_car_tree_box.className = s_car_tree_box.className.replace("tree_open","");
				}
			}
		})
	}
	//数据表选择回调
	tableTypeSelected(val){
		if(val == '1'){
			this.weightRangeTime = '5';
		}else{
			this.weightRangeTime = '30';
		}
	}
	//table刷新
    refresh(){
    	this.load();
    }
	//表格搜索
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load(){
		let timeCheck = common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId:this.TselectedCompanyId,
				deviceId:this.TdeviceId,
				status:this.Tstatus,
				type:this.Ttype,
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:common.stringTrim(this.searchKey)
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("calculateCoefLog/calculateCoefLogforpage.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
				for(let item of data.exhibitDatas){
					if(item.coef){
						let coefArr = [];
						for (let i = 0;i < item.coef.length; i++){
							let _item = item.coef[i];
							if(_item){
								let obj:any = {
									value:_item,
									index:i+1
								}
								coefArr.push(obj);
							}
						}
						item.coefT = coefArr;
					}else{
						item.coefT = [];
					}
				}
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//删除
	delRow(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http("calculateCoefLog/deleteCalculateLog.html",'id='+row.id).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	//系数计算
	calculation(){
		this.deviceIds = '';
		var tree = $('#carTree').jstree();
    	var selectedIds = tree.get_checked();   //获取所有选中节点id
    	if(selectedIds.indexOf('Root')>-1){
			selectedIds.splice(selectedIds.indexOf('Root'),1);
		}
		this.deviceIds = selectedIds;
		let deviceIdsList = selectedIds.join(',');
		if(!deviceIdsList){
			this.jsonApiService.message('请选择需要标定的车辆');
			return;
		}
		let reqdata = "deviceIdList="+deviceIdsList+'&tableType='+this.tableType+'&weightNum='+this.weightCount+
		'&beforeTime='+this.beforeTime+'&afterTime='+this.afterTime+'&recentDay='+this.weightRangeTime;
		this.jsonApiService.http2("calculateCoefLog/addCalculateCoefLog.html", reqdata).subscribe(result => {
			this.jsonApiService.message(result.message);
			if(result.success){
				this.load();
			}
		})
	}
	//手动开启自动标定
	auto_calculation(){
		this.jsonApiService.http("calculateCoefLog/calculateByHandler.html",null).subscribe(result => {
			this.jsonApiService.message(result.message);
		})
	}
	//明细报表
	exprotData(){
		var parameters = {
			companyId:this.TselectedCompanyId,
			deviceId:this.TdeviceId,
			status:this.Tstatus,
			type:this.Ttype,
			startTime:this.startTime,
			endTime:this.endTime,
			searchKey:common.stringTrim(this.searchKey)
		};
		let timeCheck=common.correctTime(parameters);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'calculateCoefLog/exportCalcuLogFile.html')
	}
	//时间change回调
	getSelectTableTime(val){
		this.startTime = val.startTime;
		this.endTime = val.endTime;
	}
	//table   搜索公司树选中回调
	companySelected2(data){
		this.TselectedCompanyId = data.companyId;
		this.TselectedCompanyName = data.companyName;
		this.TcarNumber = data.carNumber;
		this.TdeviceId = data.deviceId;
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		if(data.companyId){
			this.queryCarListByCompanyId(data.companyId);
		}else{
			this.deviceIds = '';
			this.carNumbers = '';	
			this.selectedCarNumber = [];
		}
	}
	delCarText(){
		this.deviceIds = '';
		this.carNumbers = '';	
		this.selectedCarNumber = [];
		this.initCarTree();
	}
	//打开公司树
	carClick() {
		if(this.selectedCompanyId){
			$('#s_car_tree_box').toggleClass('tree_open');
		}else{
			this.jsonApiService.message('请选择公司');
		}
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId){
		this.carList = [];
		this.deviceIds = '';
		this.carNumbers = '';	
		this.selectedCarNumber = [];
		let reqdata = 'companyId='+companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
        	var selectdata = [];
        	for(var i = 0 ; i < carlist.length ; i++) {
        		var obj = {
        			icon: "fa fa-car",
        			id:carlist[i].deviceId,
        			text:carlist[i].carNumber,
        			parent:'Root',
        			remark:'car'
        		} 
        		selectdata[i] = obj;
        	}
        	selectdata.push({
        			icon: "fa fa-home",
        			id:'Root',
        			text:'全部',
        			parent:'#',
        			remark:'Root',
        			state:{disabled: false,opened: true,selected: false}
        		})
        	this.carList = selectdata;
        	this.initCarTree()
//      	$('#carTree').jstree(true).settings.core.data = selectdata; // 新数据
//			$('#carTree').jstree(true).refresh(); //刷新树
		})
	}
	//拉取车辆数据,生成树形图
	initCarTree(){
		var that = this;
		$('#carTree').jstree("destroy");
		$('#carTree').data('jstree', false);
		$('#carTree').data('jstree', false).empty();
		$('#carTree').data('jstree', false).empty().jstree({
			"core": {
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["checkbox","search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			if(currentNode.id == 'Root'){
				that.carNumbers = '全部';
				return;
			}
			if(currentNode.state.selected){
				if(!that.selectedCarNumber.includes(currentNode.text)){
					that.selectedCarNumber.push(currentNode.text);
				}
			}else{
				that.selectedCarNumber.splice(that.selectedCarNumber.indexOf(currentNode.text),1)
			}
			that.carNumbers = that.selectedCarNumber.join(',');
		})
		if(this.carList){
			$('#carTree').jstree(true).settings.core.data = this.carList; // 新数据
			$('#carTree').jstree(true).refresh(); //刷新树
		}
		
		
	}
	carSearch(){
		var that = this;
		var value = $('#cartreeSearchInput').val();
		$('#carTree').jstree(true).search(value);
		let searchResult = $('#carTree').find('.jstree-search').length;
		if(searchResult < 1) {
			return;
		}
		$('#carTree').find('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}
}
